package com.hy.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hy.common.Result;
import com.hy.dto.collection.UserCollectionDTO;
import com.hy.entity.UserCollection;
import com.hy.entity.Weekly;
import com.hy.mapper.UserCollectionMapper;
import com.hy.service.UserCollectionService;
import com.hy.service.WeeklyService;
import com.hy.util.UserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class UserCollectionServiceImpl extends ServiceImpl<UserCollectionMapper, UserCollection> implements UserCollectionService {

    @Autowired
    private UserUtil userUtil;

    @Autowired
    private WeeklyService weeklyService;

    @Override
    public List<UserCollectionDTO> getUserCollections(Long userId) {
        // 查询用户收藏记录
        LambdaQueryWrapper<UserCollection> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserCollection::getUserId, userId)
               .eq(UserCollection::getDeleteFlag, 0)
               .orderByDesc(UserCollection::getCreateTime);
        List<UserCollection> collections = list(wrapper);
        
        if (collections.isEmpty()) {
            return new ArrayList<>();
        }
        
        // 获取所有收藏的周刊ID
        List<Integer> weeklyIds = collections.stream()
                .map(UserCollection::getCollectionId)
                .collect(Collectors.toList());
        
        // 批量查询周刊信息
        List<Weekly> weeklies = weeklyService.listByIds(weeklyIds);
        Map<Integer, Weekly> weeklyMap = weeklies.stream()
                .collect(Collectors.toMap(Weekly::getId, weekly -> weekly, (k1, k2) -> k1));
        
        // 组装DTO数据
        return collections.stream().map(collection -> {
            UserCollectionDTO dto = new UserCollectionDTO();
            BeanUtils.copyProperties(collection, dto);
            
            // 添加周刊信息
            Weekly weekly = weeklyMap.get(collection.getCollectionId());
            if (weekly != null) {
                dto.setWeeklyTitle(weekly.getWeeklyTitle());
                dto.setPdfUrl(weekly.getFileUrl());
                dto.setLikeNumbers(weekly.getLikeNumbers());
            }
            
            return dto;
        }).collect(Collectors.toList());
    }

    @Override
    @Transactional
    public Result<Void> addCollection(UserCollection userCollection) {

        // 判断是否已经收藏过
        Integer userId = userUtil.getUserIdFromToken();
        LambdaQueryWrapper<UserCollection> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserCollection::getUserId,userId);
        queryWrapper.eq(UserCollection::getCollectionId,userCollection.getCollectionId());
        UserCollection one = getOne(queryWrapper);
        if(ObjectUtil.isNotEmpty(one)){
            return Result.error("你已经收藏过了");
        }

        // 添加收藏
        userCollection.setUserId(userId);
        userCollection.setDeleteFlag(0);
        userCollection.setCreateTime(new Date());
        userCollection.setUpdateTime(new Date());
        save(userCollection);
        return Result.success("收藏成功");
    }

    @Override
    @Transactional
    public boolean cancelCollection(Long id) {
        LambdaUpdateWrapper<UserCollection> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(UserCollection::getId, id)
                    .set(UserCollection::getDeleteFlag, 1)
                    .set(UserCollection::getUpdateTime, LocalDateTime.now());
        return update(updateWrapper);
    }

    @Override
    public boolean isCollected(Long userId, Long collectionId) {
        LambdaQueryWrapper<UserCollection> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserCollection::getUserId, userId)
               .eq(UserCollection::getCollectionId, collectionId)
               .eq(UserCollection::getDeleteFlag, 0);
        return count(wrapper) > 0;
    }
} 